package com.drcoffee.drcoffeemall.util;

import com.drcoffee.drcoffeemall.mapper.BsUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@Component
public class SendWxWorlUtil {
    @Autowired
    BsUserMapper bsUserMapper;

    private RestTemplate restTemplate;

    public SendWxWorlUtil() {
        this.restTemplate = new RestTemplate();
    }

    /**
     * 用于发送订单、售后提醒至企业微信成员
     * 文档：https://developer.work.weixin.qq.com/document/path/90236
     * 消息类型：文本卡片消息
     */
    public String sendPostRequest(String url, Object requestBody) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 创建HttpEntity，包含请求体和请求头
        HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送POST请求
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);

        // 获取响应体
        return responseEntity.getBody();
    }

    public String getAccessToken() {
        String ID = "ww6813556fed7f3391";
        String SECRET = "1yt9efwfD1RCMuafhTudBferlkKgzLNANdcSutTEjBc";
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + ID + "&corpsecret=" + SECRET;
        // 发送POST请求
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        // 获取响应体
        Map<String, Object> resultMap = BodyToMapUtil.convertJsonToMap(responseEntity.getBody());
        if (resultMap.get("errmsg").equals("ok")) {
            return (String) resultMap.get("access_token");
        } else {
            return "";
        }
    }

    public static void main(String[] args) {
        String ID = "ww6813556fed7f3391";
        String SECRET = "1yt9efwfD1RCMuafhTudBferlkKgzLNANdcSutTEjBc";
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + ID + "&corpsecret=" + SECRET;
        // 发送POST请求
        RestTemplate restTemplate1 = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate1.getForEntity(url, String.class);
        // 获取响应体
        Map<String, Object> resultMap = BodyToMapUtil.convertJsonToMap(responseEntity.getBody());
        System.out.println(resultMap);
        System.out.println(resultMap.get("errmsg").equals("ok"));
    }


    public void sendAppoint(Integer schedule) {
        // 根据进度查询接收提醒人员
        List<String> qywxIdList = bsUserMapper.getWxWorkUserId(schedule);
        if (!qywxIdList.isEmpty()) {
            String title;
            String text = switch (schedule) {
                case 1 -> {
                    title = "订单提醒";
                    yield "您有一个配件订单需要处理！";
                }
                case 2 -> {
                    title = "发货提醒";
                    yield "您有一个配件订单需要发货！";
                }
                case 3 -> {
                    title = "售后提醒";
                    yield "您有一个售后申请需要审核！";
                }
                case 4 -> {
                    title = "验收提醒";
                    yield "您有一个售后退回等待验收！";
                }
                case 5 -> {
                    title = "退款提醒";
                    yield "您有一个售后退款需要审核！";
                }
                case 6 -> {
                    title = "退款提醒";
                    yield "您有一个售后退款需要执行！";
                }
                case 7 -> {
                    title = "补发提醒";
                    yield "您有一个换货订单需要补发！";
                }
                case 8 -> {
                    title = "汇款提醒";
                    yield "您有一个订单汇款需要审核！";
                }
                case 9 -> {
                    title = "开票提醒";
                    yield "您有一个订单开票申请需要处理！";
                }
                default -> {
                    title = "";
                    yield "";
                }
            };
            sendTextCard(String.join("|", qywxIdList), title, text);
        }
    }

    // 国外订单处理提醒
    public void enSendAppoint(String bs_qw_user_id) {
        sendTextCard(bs_qw_user_id, "订单提醒", "您有一个配件订单需要处理！");

    }
    public void sendTextCard(String qw_user_id, String title, String text) {
        String ACCESS_TOKEN = getAccessToken();

        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + ACCESS_TOKEN;
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("touser", qw_user_id);
        requestBody.put("toparty", "@all");
        requestBody.put("totag", "@all");
        requestBody.put("msgtype", "textcard");
        requestBody.put("agentid", 1000026);
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年M月d日", Locale.CHINA);
        String formattedDate = currentDate.format(formatter);
        Map<String, Object> textCard = new HashMap<>();
        textCard.put("title", title);
        textCard.put("description", "<div class=\"gray\">" + formattedDate + "</div> <div class=\"normal\">" + text + "</div><div class=\"highlight\">请尽快前往配件商城后台处理</div>");
//        textCard.put("url", "http://drmall.dr-coffee.com/%E6%8F%90%E7%A4%BA.txt");
        textCard.put("url", " https://drmall.dr-coffee.com/tishi.txt");
        textCard.put("btntxt", "详情");
        requestBody.put("textcard", textCard);
        requestBody.put("enable_id_trans", 0);
        requestBody.put("enable_duplicate_check", 0);
        requestBody.put("duplicate_check_interval", 1800);
        String response = sendPostRequest(url, requestBody);
        System.out.println("===============================================================================");
        System.out.println(response);
        System.out.println("===============================================================================");
    }
}
